package com.furnitur.modules.admin.service.statistics.impl;


import com.furnitur.core.mapper.order.OrderMapper;
import com.furnitur.modules.admin.dto.statistics.OrderStatisticsDTO;
import com.furnitur.modules.admin.service.merchant.MerchantService;
import com.furnitur.modules.admin.service.statistics.OrderStatisticsService;
import com.furnitur.modules.admin.vo.statistics.OrderStatisticsVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class OrderStatisticsServiceImpl implements OrderStatisticsService {

    @Autowired
    private OrderMapper orderMapper;
    
    @Autowired
    private MerchantService merchantService;

    @Override
    public OrderStatisticsVO getStatistics(OrderStatisticsDTO dto) {
        OrderStatisticsVO vo = new OrderStatisticsVO();
        
        // 获取当前商家ID
        Long merchantId = merchantService.getCurrentMerchantInfo().getId();
        
        // 设置商家ID到DTO中
        dto.setMerchantId(merchantId);
        
        // 设置统计数据
        vo.setTotalOrders(orderMapper.countTotalOrders(dto));
        vo.setTotalSales(orderMapper.sumTotalSales(dto));
        vo.setCompletionRate(calculateCompletionRate(dto));
        vo.setRefundOrders(orderMapper.countRefundOrders(merchantId));
        vo.setRefundRate(calculateRefundRate(dto));
        vo.setActiveUsers(orderMapper.countActiveUsers(dto));
        vo.setRepurchaseRate(calculateRepurchaseRate(dto));
        vo.setAverageOrderValue(calculateAverageOrderValue(dto));
        
        // 设置趋势数据
        List<Map<String, Object>> trends = orderMapper.getOrderTrends(dto);
        processTrendData(vo, trends);
        
        // 设置状态分布
        List<Map<String, Object>> distribution = orderMapper.getStatusDistribution(dto);
        processStatusDistribution(vo, distribution);
        
        return vo;
    }
    
    private Double calculateCompletionRate(OrderStatisticsDTO dto) {
        Integer total = orderMapper.countTotalOrders(dto);
        if (total == 0) {
            return 0.0;
        }
        Integer completed = orderMapper.countCompletedOrders(dto);
        return (completed * 100.0) / total;
    }

    private Double calculateRefundRate(OrderStatisticsDTO dto) {
        Integer total = orderMapper.countTotalOrders(dto);
        if (total == 0) {
            return 0.0;
        }
        Integer refunded = orderMapper.countRefundOrders(dto.getMerchantId());
        return (refunded * 100.0) / total;
    }

    private Double calculateRepurchaseRate(OrderStatisticsDTO dto) {
        Integer totalUsers = orderMapper.countActiveUsers(dto);
        if (totalUsers == 0) {
            return 0.0;
        }
        Integer repeatUsers = orderMapper.countRepeatUsers(dto);
        return (repeatUsers * 100.0) / totalUsers;
    }

    private Double calculateAverageOrderValue(OrderStatisticsDTO dto) {
        Integer totalOrders = orderMapper.countTotalOrders(dto);
        if (totalOrders == 0) {
            return 0.0;
        }
        Double totalSales = orderMapper.sumTotalSales(dto);
        return totalSales / totalOrders;
    }

    private void processTrendData(OrderStatisticsVO vo, List<Map<String, Object>> trends) {
        List<String> dates = new ArrayList<>();
        List<Integer> orderCounts = new ArrayList<>();
        
        for (Map<String, Object> trend : trends) {
            dates.add(trend.get("date").toString());
            orderCounts.add(((Number) trend.get("count")).intValue());
        }
        
        vo.setTrendDates(dates);
        vo.setTrendData(orderCounts);
    }

    private void processStatusDistribution(OrderStatisticsVO vo, List<Map<String, Object>> distribution) {
        List<OrderStatisticsVO.StatusData> statusList = new ArrayList<>();
        
        for (Map<String, Object> item : distribution) {
            OrderStatisticsVO.StatusData statusData = new OrderStatisticsVO.StatusData();
            Integer status = ((Number) item.get("status")).intValue();
            statusData.setStatus(status);
            statusData.setStatusName(getStatusName(status));
            statusData.setCount(((Number) item.get("count")).intValue());
            statusList.add(statusData);
        }
        
        vo.setStatusDistribution(statusList);
    }

    private String getStatusName(Integer status) {
        switch (status) {
            case 0: return "待付款";
            case 1: return "待发货";
            case 2: return "待收货";
            case 3: return "已完成";
            case 4: return "已取消";
            default: return "未知状态";
        }
    }
} 